/**
 * Create in 2012-9-21 下午3:36:03.
 */
package kit4j.ui.cs.swing.component;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JLabel;

/**
 * 超链接标签组件。
 * 
 * @author MiniKnife
 * 
 */
public class JLink extends JLabel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private URI linkURI;

	private boolean autoProcessTextStyle;

	/**
	 * @param text
	 */
	public JLink(String text) {
		super();
		initLink();
		setText(text);
	}

	/**
	 * @param originalText
	 */
	public JLink(URI linkURI) {
		this(linkURI.toString(), linkURI);
	}

	/**
	 * @param text
	 * @throws URISyntaxException
	 */
	public JLink(String text, String linkURI) throws URISyntaxException {
		this(text, new URI(linkURI));
	}

	/**
	 * @param text
	 */
	public JLink(String text, URI linkURI) {
		super();
		initLink();
		setText(text);
		setLinkURI(linkURI);
	}

	private void initLink() throws UnsupportedOperationException {
		// 设置鼠标手势
		setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		
		// 验证系统是否支持调用浏览器打开超链接并启用点击事件监听
		if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
			setAutoProcessTextStyle(true);
			addMouseListener(new MouseAdapter() {

				@Override
				public void mouseClicked(MouseEvent evt) {
					URI uri = getLinkURI();
					if (uri != null) {
						try {
							Desktop.getDesktop().browse(uri);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			});
		} else {
			throw new UnsupportedOperationException();
		}
	}

	/**
	 * @return the linkURI
	 */
	public URI getLinkURI() {
		return linkURI;
	}

	/**
	 * @param linkURI
	 *            the linkURI to set
	 */
	public void setLinkURI(URI linkURI) {
		this.linkURI = linkURI;
	}

	/**
	 * @return the autoProcessTextStyle
	 */
	public boolean isAutoProcessTextStyle() {
		return autoProcessTextStyle;
	}

	/**
	 * @param autoProcessTextStyle
	 *            the autoProcessTextStyle to set
	 */
	public void setAutoProcessTextStyle(boolean autoProcessTextStyle) {
		this.autoProcessTextStyle = autoProcessTextStyle;
	}

	@Override
	public void setText(String text) {
		if (isAutoProcessTextStyle()) {
			super.setText(new StringBuilder().append("<html><font color='blue'><u>").append(text)
					.append("</u></font><html>").toString());
		} else {
			super.setText(text);
		}
	}

}
